package com.geekweb.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.type.TypeFactory;

public class JacksonUtil {
	private static ObjectMapper objectMapper = new ObjectMapper();;

	public static String writeEntity2Json(Object obj) throws IOException {
		return objectMapper.writeValueAsString(obj);
	}

	@SuppressWarnings("unchecked")
	public static <T> T readJson2Entity(String jsonStr, Class clazz) throws JsonParseException, JsonMappingException,
			IOException {
		return (T) objectMapper.readValue(jsonStr, clazz);
	}

	@SuppressWarnings("unchecked")
	public static <T> List<T> readJson2List(String jsonStr, Class clazz) throws JsonParseException,
			JsonMappingException, IOException {
		return objectMapper.readValue(jsonStr, TypeFactory.defaultInstance().constructCollectionType(ArrayList.class,
				clazz));
	}

	/*public static void main(String[] args) throws IOException {
		List<ConfigHis> dataList = new ArrayList<ConfigHis>();
		ConfigHis oConfigHis = new ConfigHis();
		oConfigHis.setConfigCode("1231");
		oConfigHis.setContext("131231231");
		oConfigHis.setFilePath("12131");
		System.out.println(writeEntity2Json(oConfigHis));
		ConfigHis oConfigHis2 = (ConfigHis) readJson2Entity(writeEntity2Json(oConfigHis), ConfigHis.class);
		System.out.println(oConfigHis2.toString());
		dataList.add(oConfigHis);
		dataList.add(oConfigHis);
		System.out.println(writeEntity2Json(dataList));
		List<ConfigHis> dataListRead = readJson2List(writeEntity2Json(dataList), ConfigHis.class);
		for (ConfigHis oConfigHisRead : dataListRead) {
			System.out.println(oConfigHisRead.toString());
		}
	}*/
}
